/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 自定义广告位组件
 *  */
import React, { useState, useCallback, useEffect } from "react";
import { Row, Col, Form, List, Checkbox, Switch, Button } from "antd";
import { connect } from "dva";
import KbPreviewImage from "@/components/KbPreviewImage";
import AdvAdd from "./AdvAdd";
import AdvTable from "./AdvTable";

const FormItem = Form.Item;
const style = { fontSize: 20, fontWeight: "bold" };
const positionOptions = [
  { label: "查件页", value: "check_piece_page" },
  { label: "物流详情页", value: "logistics_details_page" },
  { label: "预约取件页", value: "subscribe_get_page" },
  { label: "订单提交页", value: "order_submit_page" },
  { label: "驿站主页", value: "stage_home_page" },
  { label: "订单详情页", value: "order_details_page" },
];
const imgList = [
  "https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/advSetting/1.png",
  "https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/advSetting/2.png",
  "https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/advSetting/3.png",
  "https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/advSetting/4.png",
  "https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/advSetting/5.png",
  "https://cdn-img.kuaidihelp.com/kb_city_web/wxSetting/advSetting/6.png",
];

const Diy = ({ form, dispatch }) => {
  const { getFieldDecorator, getFieldsValue } = form;
  const { mini_app_show, official_accounts_show } = getFieldsValue();

  const [visible, setVisible] = useState(false);
  const [modalType, setModalType] = useState("add");
  const [advDetail, setAdvDetail] = useState({});

  const getAdvList = useCallback(
    () => {
      dispatch({
        type: "wxSettings/getAdvList",
      });
    },
    [dispatch]
  );

  const onAdd = useCallback(() => {
    setVisible(true);
    setModalType("add");
    setAdvDetail({});
  }, []);

  const onEditAdv = useCallback((advInfo = {}) => {
    setVisible(true);
    setModalType("edit");
    setAdvDetail(advInfo);
  }, []);

  useEffect(
    () => {
      dispatch({
        type: "wxSettings/getAdvSetting",
      });
      getAdvList();
    },
    [dispatch, getAdvList]
  );

  return (
    <div>
      <Row type="flex" justify="space-between" align="middle">
        <Col>
          <h2>广告开启平台及位置</h2>
        </Col>
        <Col>
          <KbPreviewImage type="check" imgWidth={500} src={imgList}>
            <a>查看示意图</a>
          </KbPreviewImage>
        </Col>
      </Row>
      <Form layout="inline">
        <List bordered>
          <List.Item>
            <Row type="flex" align="middle" style={{ width: "100%" }}>
              <Col style={style} xs={24} sm={4}>
                <FormItem label="小程序">
                  {getFieldDecorator("mini_app_show", {
                    valuePropName: "checked",
                  })(<Switch checkedChildren="关" unCheckedChildren="开" />)}
                </FormItem>
              </Col>
              <Col xs={24} sm={20}>
                <FormItem>
                  {getFieldDecorator("miniCheckBox")(
                    <Checkbox.Group disabled={!mini_app_show} options={positionOptions} />
                  )}
                </FormItem>
              </Col>
            </Row>
          </List.Item>
          <List.Item>
            <Row type="flex" align="middle" style={{ width: "100%" }}>
              <Col style={style} xs={24} sm={4}>
                <FormItem label="公众号">
                  {getFieldDecorator("official_accounts_show", {
                    valuePropName: "checked",
                  })(<Switch checkedChildren="关" unCheckedChildren="开" />)}
                </FormItem>
              </Col>
              <Col xs={24} sm={20}>
                <FormItem>
                  {getFieldDecorator("officialCheckBox")(
                    <Checkbox.Group disabled={!official_accounts_show} options={positionOptions} />
                  )}
                </FormItem>
              </Col>
            </Row>
          </List.Item>
        </List>
      </Form>
      <Row
        type="flex"
        justify="space-between"
        align="middle"
        style={{ marginTop: 15, marginBottom: 15 }}
      >
        <Col style={style}>广告列表（最多5个）</Col>
        <Col>
          <Button type="primary" onClick={onAdd}>
            添加广告
          </Button>
        </Col>
      </Row>
      <AdvTable onEditAdv={onEditAdv} getList={getAdvList} />
      <AdvAdd
        visible={visible}
        onVisibleChange={setVisible}
        type={modalType}
        getList={getAdvList}
        record={advDetail}
      />
    </div>
  );
};

export default connect(({ wxSettings }) => ({
  advSetting: wxSettings.advSetting,
}))(
  Form.create({
    mapPropsToFields: props => {
      const { advSetting = {} } = props;
      const {
        mini_app_show = false,
        official_accounts_show = false,
        mini_app_checkBox = [],
        official_accounts_checkBox = [],
      } = advSetting;
      return {
        mini_app_show: Form.createFormField({
          value: mini_app_show,
        }),
        miniCheckBox: Form.createFormField({
          value: mini_app_checkBox,
        }),
        official_accounts_show: Form.createFormField({
          value: official_accounts_show,
        }),
        officialCheckBox: Form.createFormField({
          value: official_accounts_checkBox,
        }),
      };
    },
    onValuesChange: (props, changedValue, allValues) => {
      const { dispatch } = props;
      const {
        mini_app_show,
        official_accounts_show,
        miniCheckBox = [],
        officialCheckBox = [],
      } = allValues;

      // 是否是小程序的设置
      const isMiniAppChange = ["mini_app_show", "miniCheckBox"].includes(
        Object.keys(changedValue)[0]
      );

      const official_accounts = {
        status: official_accounts_show ? 2 : 1,
        platform_type: 2,
      };
      const mini_app = {
        status: mini_app_show ? 2 : 1,
        platform_type: 1,
      };
      const checkBoxObj = {
        check_piece_page: 1,
        logistics_details_page: 1,
        subscribe_get_page: 1,
        order_submit_page: 1,
        stage_home_page: 1,
        order_details_page: 1,
      };

      for (const key in checkBoxObj) {
        if (Object.hasOwnProperty.call(checkBoxObj, key)) {
          if (isMiniAppChange) {
            mini_app[key] = miniCheckBox.includes(key) ? 2 : 1;
          } else {
            official_accounts[key] = officialCheckBox.includes(key) ? 2 : 1;
          }
        }
      }

      dispatch({
        type: "wxSettings/setAdv",
        payload: isMiniAppChange ? mini_app : official_accounts,
      })
        .then(() => {
          dispatch({
            type: "wxSettings/getAdvSetting",
          });
        })
        .catch(() => {
          dispatch({
            type: "wxSettings/getAdvSetting",
          });
        });
    },
  })(React.memo(Diy))
);
